<!--
 * @Description: 确认订单页面组件
 * @Author: hai-27
 * @Date: 2020-02-23 23:46:39
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-29 13:10:21
 -->



<template>
  <div class="confirmOrder">
    <!-- 头部 -->
    <div class="confirmOrder-header">
      <div class="header-content">
        <p>
          <i class="el-icon-s-order"></i>
        </p>
        <p>确认订单</p>
        <router-link to></router-link>
      </div>
    </div>
    <!-- 头部END -->

    <!-- 主要内容容器 -->
    <div class="content">
      <!-- 选择地址 -->
      <div class="section-address">
        <p class="title">收货地址</p>
        <div class="address-body">
          <ul>
            <li
                :class="item.id == confirmAddress ? 'in-section' : ''"
                v-for="item in address"
                :key="item.id"
                @click="selectAddress(item.id)"
            >
              <h2>{{item.receiver}}</h2>
              <p class="phone">{{item.phone}}</p>
              <p class="address">{{item.region.fullName}}{{item.regionDetail}}</p>
            </li>
            <li class="add-address" @click="showAddAddressDialog">
              <i class="el-icon-circle-plus-outline"></i>
              <p>添加新地址</p>
            </li>
          </ul>
        </div>
      </div>
      <!-- 选择地址END -->

      <!-- 添加地址对话框 -->
      <el-dialog title="添加新地址" :visible.sync="addAddressDialogVisible" width="500px">
        <el-form :model="newAddress" :rules="addressRules" ref="addressForm" label-width="80px">
          <el-form-item label="收货人" prop="receiver">
            <el-input v-model="newAddress.receiver" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="newAddress.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="regionId">
            <el-cascader
                v-model="selectedRegion"
                :options="regionOptions"
                :props="regionProps"
                placeholder="请选择所在地区"
                @change="handleRegionChange"
                style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="regionDetail">
            <el-input
                v-model="newAddress.regionDetail"
                placeholder="请输入详细地址，如道路、门牌号等"
                type="textarea">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addAddressDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addNewAddress">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加地址对话框END -->

      <!-- 商品及优惠券 -->
      <div class="section-goods">
        <p class="title">商品及优惠券</p>
        <div class="goods-list">
          <ul>
            <li v-for="item in getCheckGoods" :key="item.id">
              <img :src="item.good.pic" />
              <span class="pro-name">{{item.good.name}}</span>
              <span class="pro-price">{{item.good.price}}元 x {{item.qty}}</span>
              <span class="pro-status"></span>
              <span class="pro-total">{{item.good.price * item.qty}}元</span>
            </li>
          </ul>
        </div>
      </div>
      <!-- 商品及优惠券END -->

      <!-- 配送方式 -->
      <div class="section-shipment">
        <p class="title">配送方式</p>
        <p class="shipment">包邮</p>
      </div>
      <!-- 配送方式END -->

      <!-- 发票 -->
      <div class="section-invoice">
        <p class="title">发票</p>
        <p class="invoice">电子发票</p>
        <p class="invoice">个人</p>
        <p class="invoice">商品明细</p>
      </div>
      <!-- 发票END -->

      <!-- 结算列表 -->
      <div class="section-count">
        <div class="money-box">
          <ul>
            <li>
              <span class="title">商品件数：</span>
              <span class="value">{{getCheckNum}}件</span>
            </li>
            <li>
              <span class="title">商品总价：</span>
              <span class="value">{{getMarketPrice}}元</span>
            </li>
            <li>
              <span class="title">活动优惠：</span>
              <span class="value">-{{getMarketPrice - getTotalPrice}}元</span>
            </li>
            <li>
              <span class="title">优惠券抵扣：</span>
              <span class="value">-0元</span>
            </li>
            <li>
              <span class="title">运费：</span>
              <span class="value">0元</span>
            </li>
            <li class="total">
              <span class="title">应付总额：</span>
              <span class="value">
                <span class="total-price">{{getTotalPrice}}</span>元
              </span>
            </li>
          </ul>
        </div>
      </div>
      <!-- 结算列表END -->

      <!-- 结算导航 -->
      <div class="section-bar">
        <div class="btn">
          <router-link to="/shoppingCart" class="btn-base btn-return">返回购物车</router-link>
          <a href="javascript:void(0);" @click="addOrder" class="btn-base btn-primary">结算</a>
        </div>
      </div>
      <!-- 结算导航END -->
    </div>
    <!-- 主要内容容器END -->
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { mapActions } from "vuex";

export default {
  name: "",
  data() {
    return {
      confirmAddress: 0, // 选择的地址id
      orderComment: '',  // 订单备注
      address: [],       // 地址列表，初始为空数组
      loading: false,    // 加载状态

      // 添加地址相关
      addAddressDialogVisible: false,
      newAddress: {
        memberId: 0,
        receiver: '',
        phone: '',
        regionId: null,
        regionDetail: ''
      },
      selectedRegion: [],
      regionOptions: [],
      regionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover'
      },
      addressRules: {
        receiver: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        regionId: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        regionDetail: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.getUserAddresses();
    this.getRegionTree();
  },
  created() {
    // 如果没有勾选购物车商品直接进入确认订单页面,提示信息并返回购物车
    if (this.getCheckNum < 1) {
      this.notifyError("请勾选商品后再结算");
      this.$router.push({ path: "/shoppingCart" });
    }

    // 获取用户地址信息
    this.getUserAddresses();
  },
  computed: {
    // 结算的商品数量; 结算商品总计; 结算商品信息
    ...mapGetters(["getCheckNum", "getTotalPrice", "getCheckGoods", "getMarketPrice"])
  },
  methods: {
    ...mapActions(["deleteShoppingCart"]),

    selectAddress(addressId) {
      this.confirmAddress = addressId;
    },

    // 显示添加地址对话框
    showAddAddressDialog() {
      // 初始化用户ID
      this.newAddress.memberId = parseInt(localStorage.getItem("userId")) || 0;
      // 清空表单
      this.newAddress.receiver = '';
      this.newAddress.phone = '';
      this.newAddress.regionId = null;
      this.newAddress.regionDetail = '';
      this.selectedRegion = [];
      this.addAddressDialogVisible = true;
    },

    // 获取地区树形结构
    async getRegionTree() {
      try {
        const res = await this.$axios.get("/api/v1/address/regions/tree");
        if (res.data.code === 200) {
          this.regionOptions = res.data.data;
        }
      } catch (error) {
        console.error("获取地区信息失败:", error);
        this.notifyError("获取地区信息失败");
      }
    },

    // 地区选择变化处理
    handleRegionChange(value) {
      if (value && value.length > 0) {
        this.newAddress.regionId = value[value.length - 1];
      } else {
        this.newAddress.regionId = null;
      }
    },

    // 添加新地址
    addNewAddress() {
      this.$refs.addressForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await this.$axios.post("/api/v1/address/add", this.newAddress);
            if (res.data.code === 200) {
              this.notifySucceed("地址添加成功");
              this.addAddressDialogVisible = false;
              // 重新获取地址列表
              await this.getUserAddresses();
            } else {
              this.notifyError(res.data.msg || "地址添加失败");
            }
          } catch (error) {
            console.error("添加地址失败:", error);
            this.notifyError("添加地址失败，请重试");
          }
        }
      });
    },

    // 获取当前登录用户的地址列表
    async getUserAddresses() {
      try {
        this.loading = true;

        // 从localStorage获取用户ID
        const userId = parseInt(localStorage.getItem("userId"));
        if (!userId) {
          this.notifyError("用户未登录或会话已过期");
          this.$router.push("/login");
          return;
        }

        // 调用后端API获取所有地址
        const res = await this.$axios.get("/api/v1/address/get/"+userId);

        if (res.data.code === 200) {
          // 过滤出当前用户的地址（根据memberId匹配）
          this.address = res.data.data.filter(item => item.memberId === userId);

          // 如果有地址，默认选择第一个
          if (this.address.length > 0) {
            this.confirmAddress = this.address[0].id;
          } else {
            this.notifyWarning("您还没有收货地址，请添加新地址");
          }
        } else {
          this.notifyError(res.data.msg || "获取地址信息失败");
        }
      } catch (error) {
        console.error("获取地址信息失败:", error);

        // 特别处理503错误
        if (error.response && error.response.status === 503) {
          this.notifyError("地址服务暂时不可用，请稍后再试");
        } else if (error.response && error.response.status === 401) {
          this.notifyError("登录已过期，请重新登录");
          this.$router.push("/login");
        } else {
          this.notifyError("获取地址信息异常，请检查网络连接");
        }
      } finally {
        this.loading = false;
      }
    },

    addOrder() {
      // 检查是否有地址
      if (this.address.length === 0) {
        this.notifyError("请先添加收货地址");
        return;
      }

      // 查找选中的地址
      const selectedAddress = this.address.find(addr => addr.id === this.confirmAddress);
      if (!selectedAddress) {
        this.notifyError("请选择收货地址");
        return;
      }

      this.$axios
          .post("/api/v1/order/submit", {
            memberId: parseInt(localStorage.getItem("userId")),
            cartGoods: {
              goods: this.getCheckGoods,
              marketPrice: this.getMarketPrice,
              price: this.getTotalPrice
            },
            address: selectedAddress,
            orderComment: this.orderComment
          })
          .then(res => {
            let products = this.getCheckGoods;
            if(res.data.data){
              for (let i = 0; i < products.length; i++) {
                const temp = products[i];
                // 删除已经结算的购物车商品
                this.deleteShoppingCart(temp.id);
              }
              // 提示结算结果
              this.notifySucceed(res.data.msg);
              // 跳转我的订单页面
              this.$router.push({ path: "/order" });
            } else {
              // 提示失败信息
              this.notifyError(res.data.msg);
            }
          })
          .catch(err => {
            console.error("提交订单失败:", err);

            // 处理订单提交的503错误
            if (err.response && err.response.status === 503) {
              this.notifyError("订单服务暂时不可用，请稍后再试");
            } else {
              this.notifyError("提交订单失败，请重试");
            }
          });
    }
  }
};
</script>



<style scoped>
.confirmOrder {
  background-color: #f5f5f5;
  padding-bottom: 20px;
}
/* 头部CSS */
.confirmOrder .confirmOrder-header {
  background-color: #fff;
  border-bottom: 2px solid #ff6700;
  margin-bottom: 20px;
}
.confirmOrder .confirmOrder-header .header-content {
  width: 1225px;
  margin: 0 auto;
  height: 80px;
}
.confirmOrder .confirmOrder-header .header-content p {
  float: left;
  font-size: 28px;
  line-height: 80px;
  color: #424242;
  margin-right: 20px;
}
.confirmOrder .confirmOrder-header .header-content p i {
  font-size: 45px;
  color: #ff6700;
  line-height: 80px;
}
/* 头部CSS END */

/* 主要内容容器CSS */
.confirmOrder .content {
  width: 1225px;
  margin: 0 auto;
  padding: 48px 0 0;
  background-color: #fff;
}

/* 选择地址CSS */
.confirmOrder .content .section-address {
  margin: 0 48px;
  overflow: hidden;
}
.confirmOrder .content .section-address .title {
  color: #333;
  font-size: 18px;
  line-height: 20px;
  margin-bottom: 20px;
}
.confirmOrder .content .address-body li {
  float: left;
  color: #333;
  width: 220px;
  height: 178px;
  border: 1px solid #e0e0e0;
  padding: 15px 24px 0;
  margin-right: 17px;
  margin-bottom: 24px;
}
.confirmOrder .content .address-body .in-section {
  border: 1px solid #ff6700;
}
.confirmOrder .content .address-body li h2 {
  font-size: 18px;
  font-weight: normal;
  line-height: 30px;
  margin-bottom: 10px;
}
.confirmOrder .content .address-body li p {
  font-size: 14px;
  color: #757575;
}
.confirmOrder .content .address-body li .address {
  padding: 10px 0;
  max-width: 180px;
  max-height: 88px;
  line-height: 22px;
  overflow: hidden;
}
.confirmOrder .content .address-body .add-address {
  text-align: center;
  line-height: 30px;
}
.confirmOrder .content .address-body .add-address i {
  font-size: 30px;
  padding-top: 50px;
  text-align: center;
}
/* 选择地址CSS END */

/* 商品及优惠券CSS */
.confirmOrder .content .section-goods {
  margin: 0 48px;
}
.confirmOrder .content .section-goods p.title {
  color: #333;
  font-size: 18px;
  line-height: 40px;
}
.confirmOrder .content .section-goods .goods-list {
  padding: 5px 0;
  border-top: 1px solid #e0e0e0;
  border-bottom: 1px solid #e0e0e0;
}
.confirmOrder .content .section-goods .goods-list li {
  padding: 10px 0;
  color: #424242;
  overflow: hidden;
}
.confirmOrder .content .section-goods .goods-list li img {
  float: left;
  width: 30px;
  height: 30px;
  margin-right: 10px;
}
.confirmOrder .content .section-goods .goods-list li .pro-name {
  float: left;
  width: 650px;
  line-height: 30px;
}
.confirmOrder .content .section-goods .goods-list li .pro-price {
  float: left;
  width: 150px;
  text-align: center;
  line-height: 30px;
}
.confirmOrder .content .section-goods .goods-list li .pro-status {
  float: left;
  width: 99px;
  height: 30px;
  text-align: center;
  line-height: 30px;
}
.confirmOrder .content .section-goods .goods-list li .pro-total {
  float: left;
  width: 190px;
  text-align: center;
  color: #ff6700;
  line-height: 30px;
}
/* 商品及优惠券CSS END */

/* 配送方式CSS */
.confirmOrder .content .section-shipment {
  margin: 0 48px;
  padding: 25px 0;
  border-bottom: 1px solid #e0e0e0;
  overflow: hidden;
}
.confirmOrder .content .section-shipment .title {
  float: left;
  width: 150px;
  color: #333;
  font-size: 18px;
  line-height: 38px;
}
.confirmOrder .content .section-shipment .shipment {
  float: left;
  line-height: 38px;
  font-size: 14px;
  color: #ff6700;
}
/* 配送方式CSS END */

/* 发票CSS */
.confirmOrder .content .section-invoice {
  margin: 0 48px;
  padding: 25px 0;
  border-bottom: 1px solid #e0e0e0;
  overflow: hidden;
}
.confirmOrder .content .section-invoice .title {
  float: left;
  width: 150px;
  color: #333;
  font-size: 18px;
  line-height: 38px;
}
.confirmOrder .content .section-invoice .invoice {
  float: left;
  line-height: 38px;
  font-size: 14px;
  margin-right: 20px;
  color: #ff6700;
}
/* 发票CSS END */

/* 结算列表CSS */
.confirmOrder .content .section-count {
  margin: 0 48px;
  padding: 20px 0;
  overflow: hidden;
}
.confirmOrder .content .section-count .money-box {
  float: right;
  text-align: right;
}
.confirmOrder .content .section-count .money-box .title {
  float: left;
  width: 126px;
  height: 30px;
  display: block;
  line-height: 30px;
  color: #757575;
}
.confirmOrder .content .section-count .money-box .value {
  float: left;
  min-width: 105px;
  height: 30px;
  display: block;
  line-height: 30px;
  color: #ff6700;
}
.confirmOrder .content .section-count .money-box .total .title {
  padding-top: 15px;
}
.confirmOrder .content .section-count .money-box .total .value {
  padding-top: 10px;
}
.confirmOrder .content .section-count .money-box .total-price {
  font-size: 30px;
}
/* 结算列表CSS END */

/* 结算导航CSS */
.confirmOrder .content .section-bar {
  padding: 20px 48px;
  border-top: 2px solid #f5f5f5;
  overflow: hidden;
}
.confirmOrder .content .section-bar .btn {
  float: right;
}
.confirmOrder .content .section-bar .btn .btn-base {
  float: left;
  margin-left: 30px;
  width: 158px;
  height: 38px;
  border: 1px solid #b0b0b0;
  font-size: 14px;
  line-height: 38px;
  text-align: center;
}
.confirmOrder .content .section-bar .btn .btn-return {
  color: rgba(0, 0, 0, 0.27);
  border-color: rgba(0, 0, 0, 0.27);
}
.confirmOrder .content .section-bar .btn .btn-primary {
  background: #ff6700;
  border-color: #ff6700;
  color: #fff;
}
/* 结算导航CSS */

/* 主要内容容器CSS END */
</style>